package com.yyk.springservicetwo.config;

import com.yyk.config.commonService.enumeration.HttpStatusEnum;
import com.yyk.config.commonService.exception.YYKCloudException;
import com.yyk.config.commonService.response.YYKCloudResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 功能说明：对内部接口返回结果做处理，状态码不正常则向上抛出异常
 *
 * @author
 * @date
 **/
@Aspect
@Component
@Order(100)
public class ClientAspect {

    private static Logger logger = LoggerFactory.getLogger(ClientAspect.class);

    /**
     * 为了避免实现类也误打内部接口日志，所以在拦截到的时候判断下是否为实现类，若是实现类则不拦截
     */
    private final static String FEIGN_IMPL = "Facade";

    @Pointcut("execution( * com..*.facade..*.*(..))")
    public void clientLog(){}

    @Around("clientLog()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {


        Object result;
        long timeStart = System.currentTimeMillis();

        String label = pjp.getSignature().getDeclaringType().getSimpleName() + "_" + pjp.getSignature().getName();

        logger.info("调用内部接口 " + label + " 开始 ");
        try{
            result = pjp.proceed();
            YYKCloudResponse serviceResponse = (YYKCloudResponse)result;
            if(!serviceResponse.getCode().equals(HttpStatusEnum.HTTP_OK.getCode())){
                throw new YYKCloudException(serviceResponse.getCode(), serviceResponse.getMessage());
            }
        }catch (YYKCloudException we){
            logger.error("自定义业务异常: " + label + " " + we.getMessage());
            throw we;
        }catch (Exception e){
            logger.error("系统异常: " + label + " " + e.getMessage(), e);
            throw e;
        }finally {
            logger.info("调用内部接口 " + label + " 结束 " + " 共耗时 "+(System.currentTimeMillis() - timeStart) + "毫秒");
        }
        return result;
    }
}
